<template>
  <div id="app">
    <div class="preload" v-if="removeLogin">
      <div class="container">
        <p class="name">
          {{ systemCode == "business" ? "智厨业务管理系统" : "伙食保障精细管理系统" }}
        </p>
        <p class="title">正在进行页面跳转...</p>
        <p class="sub-title">初次加载资源可能需要较多时间 请耐心等待</p>
      </div>

      <div class="footer">
        <a href="" target="_blank"
          >{{ systemCode == "business" ? "智厨业务管理系统" : "伙食保障精细管理系统" }}
        </a>
      </div>
    </div>
    <router-view  />
  </div>
</template>

<script>
import { firstRouter, errRouters } from "@/router/routers";
import { postPermissionForRoleId, getUserBaseInfo, login } from "@/api/organ/system";
import iView from "view-design";
import User from "./components/main/components/user";

export default {
  name: "App",
  data() {
    return {
      removeLogin: false,
      systemCode: localStorage.getItem("systemCode"),
    };
  },
  created() {
    if (this.vuex_user.token) this.$store.dispatch("getAreaListApi");
  },
  mounted() {

    this.onInit();
    this.$cu.eventBus.$on("onRedirectGet", (path) => this.onInit(path));
    this.$cu.eventBus.$on("onLogout", () => {
      this.ws ? this.ws.onclose() : "";
      location.reload();
    });
  },
  methods: {
    onInit() {
      return new Promise((resolve) => {
        // 判断端口号
        const currentUrl = window.location.port;
        if (!window.localStorage.getItem("systemCode")) {
          let systemCode = currentUrl == 4200 ? "business" : "organ";
          window.localStorage.setItem("systemCode", systemCode);
        }
      
        // 如果地址栏包含 user 、password 、 tokens，代表是综合管理系统跳转过来的，需要走默认登录流程,且不是跟登录的为同一个用户
        if (
          this.getUrlKey("user") &&
          this.getUrlKey("password") &&
          this.getUrlKey("tokens")
        ) {
    
          this.vuex_user.token = this.getUrlKey("tokens");
          // this.removeLoginApi();
          this.$store.dispatch("getAreaListApi");
        }
        if (this.vuex_user.token) {
          iView.LoadingBar.start();
          Promise.all([this.getUserBaseInfoApi()]).then(() => {
            this.postPermissionForRoleIdApi().then(() => {
              if (this.$route.path === "/login") {
                this.$router.push({
                  path: "/home",
                });
              }
              iView.LoadingBar.finish();
              resolve();
            });
          });
        }
      });
    },
    // 添加子菜单函数
    addChildren(route) {
      this.$store.state.user.routerChildren.forEach((items) => {
 
        route.forEach((item, index) => {
   
          if (item.url == items.data.superiorPath) {
            if (item.children.find((r) => r.path === items.data.url)) {
              // 已存在路由不会重复添加
              return;
            }
            item.children.push(items.data);
      
          } else if (item.children.length > 0) {
            this.addChildren(item.children);
          } else {
          }
        });
      });
    },
    readNodes(nodes = [], arr = []) {
      for (let item of nodes) {
        arr.push(item);
        item.title = item.name;
        item.path = item.url;
        item.meta = {
          icon: item.icon,
          title: item.title,
        };
        item.selected = false;
        if (item.children && item.children.length && item.resourceType === 1) {
          item.component = () => import("@/components/parent-view/parent-view.vue");
        } else {
          item.component = () => import(`@/${item.filePath}`);
        }
        if (item.children && item.children.length) this.readNodes(item.children, arr);
      }
      return arr;
    },
    // 角色id换权限
    postPermissionForRoleIdApi() {
      return new Promise((resolve) => {
        let roles = this.$cu.deepClone(this.vuex_user.role);
        roles = roles.map((v) => {
      
          v = v.id;
          return v;
        });
        postPermissionForRoleId({
          roles: roles,
          returnSystem: false,
          systemCode: window.localStorage.getItem("systemCode"),
        }).then((res) => {
          if (res.code === 1) {
           
            let arr = [];
            res.data.map((item) => {
              // 暂时没有单点登录去掉判断 && item.type.indexOf("6")
              if (item.type != null > -1) {
                arr.push(item);
              }
            });
            // this.addChildren(arr);
            this.readNodes(arr, firstRouter);
            firstRouter[0].children = arr;
        
            this.$store.commit("$uStore", {
              name: "vuex_routers",
              value: firstRouter,
            });
            firstRouter.forEach((val) => {
             
              this.$router.addRoute(val);
            });
            errRouters.forEach((val) => {
            
              this.$router.addRoute(val);
            });
            
            resolve();
          }
        });
      });
    },
    // 获取用户基础信息
    getUserBaseInfoApi() {
      return new Promise((resolve) => {
        getUserBaseInfo({}).then((res) => {
          if (res.code === 1) {
            res.data.token = this.vuex_user.token;
            this.$store.commit("$uStore", {
              name: "vuex_user",
              value: res.data,
            });
            resolve();
          }
        });
      });
    },
    // 单点登录
    removeLoginApi() {
      return new Promise((resolve) => {
        login({
          loginName: this.getUrlKey("user"),
          password: this.getUrlKey("password"),
          token: this.getUrlKey("tokens"),
        }).then((res) => {
          if (res.code === 1) {
            this.$store.commit("$uStore", {
              name: "vuex_user",
              value: res.data,
            });
            this.getUserBaseInfoApi(res.data).then(() => {
              this.postPermissionForRoleIdApi().then(() => {
                this.removeLogin = false;
                // console.log('单点登录 2--------');
                let path = this.getUrlKey("path");
                this.$router.replace(path);
              });
            });
          }
        });
      });
    },
    getUrlKey(name) {
      return (
        decodeURIComponent(
          (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
            location.href
          ) || [, ""])[1].replace(/\+/g, "%20")
        ) || null
      );
    },
  },
};
</script>

<style lang="less">
@import "./assets/style/reset";
@import "./assets/style/business";

html,
body {
  overflow: hidden;
  margin: 0;
  padding: 0;
}

* {
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

body {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", Arial, sans-serif;
  font-size: 12px;
  line-height: 1.5;
  color: #515a6e;
  background-color: #fff;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
</style>
<style scoped>
.preload {
  display: flex;
  flex-direction: column;
  height: 100%;
  letter-spacing: 1px;
  background-color: #2f3447;
}

.preload .container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  user-select: none;
  flex-grow: 1;
}

.preload .name {
  font-size: 30px;
  color: #fff;
  letter-spacing: 5px;
  font-weight: bold;
}

.preload .title {
  color: #fff;
  font-size: 14px;
  margin: 20px;
}

.preload .sub-title {
  color: #ababab;
  font-size: 12px;
}

.preload .footer {
  text-align: center;
  padding: 10px 0 20px 0;
}

.preload .footer a {
  font-size: 12px;
  color: #ababab;
  text-decoration: none;
}
</style>
